import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'Odometer' }
      },
      {
        path: '/coupon',
        name: 'Coupon',
        component: () => import('@/views/coupon/Index.vue'),
        meta: { title: '优惠券管理', icon: 'Ticket' }
      },
      {
        path: '/coupon/create',
        name: 'CouponCreate',
        component: () => import('@/views/coupon/Create.vue'),
        meta: { title: '创建优惠券', hidden: true }
      },
      {
        path: '/coupon/edit/:id',
        name: 'CouponEdit',
        component: () => import('@/views/coupon/Edit.vue'),
        meta: { title: '编辑优惠券', hidden: true }
      },
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/user/Index.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: '/statistics',
        name: 'Statistics',
        component: () => import('@/views/statistics/Index.vue'),
        meta: { title: '数据统计', icon: 'DataAnalysis' }
      },
      {
        path: '/ai',
        name: 'AI',
        component: () => import('@/views/ai/Index.vue'),
        meta: { title: 'AI策略', icon: 'MagicStick' }
      },
      {
        path: '/settings',
        name: 'Settings',
        component: () => import('@/views/settings/Index.vue'),
        meta: { title: '系统设置', icon: 'Setting' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
  } else if (to.path === '/login' && userStore.isLoggedIn) {
    next('/')
  } else {
    next()
  }
})

export default router
